import axios from "axios";
import { ElMessage } from "element-plus";

// 创建 axios 实例
const httpInstace = axios.create({
  baseURL: "http://localhost:8085/ssm/",
  timeout: 5000,
});

const NETWORK_ERROR = "网络错误。。";

// 请求拦截器
httpInstace.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
httpInstace.interceptors.response.use(
  (response) => {
    const { code, data, message } = response.data;

    if (code === 200) {
      return data;
    } else if (code === 204) {
      return null;
    } else {
        console.log(message);
      ElMessage.error(message || NETWORK_ERROR);
      return Promise.reject(message || NETWORK_ERROR);
    }
  },
  (error) => {
    // 错误处理
    ElMessage.error(NETWORK_ERROR);
    return Promise.reject(error);
  }
);

// 请求函数
function request(option) {
  option.method = option.method || "get";
  return httpInstace(option);
}

export default request;
